package com.xy.frame.controller;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Map;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xy.frame.IConstants;
import com.xy.frame.WEBApp;
import com.xy.frame.model.AjaxJson;
import com.xy.frame.model.SessionUser;
import com.xy.frame.service.LoginService;

/**
 * @author Administrator 登录页面相关请求
 */
@Controller
@RequestMapping("login")
public class IndexController {
	Logger logger = LoggerFactory.getLogger(IndexController.class);

	@Autowired
	private LoginService loginService;

	/**
	 * 登录页面
	 * 
	 * @param request
	 * @param session
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "", method = RequestMethod.GET)
	public String login(HttpServletRequest request, HttpSession session,
			Model model) {

		// 用户登录页面加载
		int i = new Random().nextInt(3) + 1;

		String stl = request.getParameter("stl");
		if (stl != null) {
			// 找不到样式不出错
			if (WEBApp.getCODE("stl", stl) != null) {
				i = Integer.valueOf(WEBApp.getCODE("stl", stl).toString());
			}
		}
		if (logger.isDebugEnabled()) {
			logger.debug("请求【/login】响应页面【/view/index/login" + i + ".jsp】");
		}
		i = 2;// 只做一种样式
		session.setAttribute("STL_INDEX", i);
		// 记录SESSION 0,1,2,3
		return "index/login" + i;
	}

	/**
	 * 退出
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/exit", method = RequestMethod.GET)
	public String exit(HttpSession session) {
		AjaxJson j = new AjaxJson();
		session.removeAttribute(IConstants.SESSION_USER);
		Integer i = (Integer) session.getAttribute("STL_INDEX");
		session.removeAttribute("STL_INDEX");
		if (logger.isDebugEnabled()) {
			logger.debug("请求【/exit】响应结果【" + j + "】");
		}
		if (i == null) {
			i = 2;
		}
		return "index/login" + i;
	}
	
	/**
	 * 退出
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/timeout", method = RequestMethod.GET)
	public String timeout(HttpSession session) {
		if (logger.isDebugEnabled()) {
			logger.debug("请求【/timeout】响应页面【/view/errors/tologin】");
		}
		return "errors/tologin" ;
	}
	/**
	 * 锁屏
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/lock", method = RequestMethod.GET)
	public String lock(HttpSession session) {
		if (logger.isDebugEnabled()) {
			logger.debug("请求【/lock】响应页面【/view/index/lock.jsp】");
		}
		return "index/lock";
	}

	/**
	 * 登录验证
	 * 
	 * @param loginName
	 * @param loginPwd
	 * @param session
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/check", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public AjaxJson check(@RequestParam String loginName,
			@RequestParam String loginPwd, HttpSession session,
			HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		// 验证用户是否登录成功
		Map<String, Object> userMap = loginService.loginCheck(loginName,
				loginPwd);
		if (userMap != null && !userMap.isEmpty()) {
			SessionUser userBean = new SessionUser();
			userBean.setLoginName(loginName);
			userBean.setUserImg(userMap.get("F_USER_IMG") == null ? "default"
					: userMap.get("F_USER_IMG").toString());
			userBean.setUserName(userMap.get("F_USER_NAME").toString());
			session.setAttribute(IConstants.SESSION_USER, userBean);
			j.setObj("metro");// 默认系统查询
		} else {
			j.setSuccess(false);
			j.setMsg("登录失败，用户名或密码不正确！");
		}
		if (logger.isDebugEnabled()) {
			logger.debug("请求【/login/check】响应结果【" + j + "】");
		}
		return j;
	}

	/**
	 * 验证码
	 * 
	 * @param request
	 * @param response
	 * @param session
	 * @throws IOException
	 */
	@RequestMapping(value = "/code", method = RequestMethod.GET)
	public void code(HttpServletRequest request, HttpServletResponse response,
			HttpSession session) throws IOException {
		response.setContentType("image/jpeg");
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);

		int width = 48, height = 18;
		BufferedImage image = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);

		Graphics g = image.getGraphics();

		Random random = new Random();

		g.setColor(getRandColor(200, 250));
		g.fillRect(0, 0, width, height);

		g.setFont(new Font("Times New Roman", Font.BOLD, 18));

		g.setColor(getRandColor(160, 200));
		for (int i = 0; i < 80; i++) {
			int x = random.nextInt(width);
			int y = random.nextInt(height);
			int xl = random.nextInt(12);
			int yl = random.nextInt(12);
			g.drawLine(x, y, x + xl, y + yl);
		}

		String sRand = "";
		int RandNum = 15;
		int UpNum = 18;
		int DownNum = 14;
		RandNum = random.nextInt(10);
		for (int i = 0; i < 4; i++) {
			String rand = String.valueOf(random.nextInt(10));
			sRand += rand;
			g.setColor(new Color(20 + random.nextInt(110), 20 + random
					.nextInt(110), 20 + random.nextInt(110)));
			// g.setColor(Color.BLACK);
			if (RandNum % 2 == 0) {
				if ((i == 1) || (i == 3)) {
					g.drawString(rand, 10 * i + 3, UpNum);
				} else {
					g.drawString(rand, 10 * i + 3, DownNum);
				}
			} else {
				if ((i == 1) || (i == 3)) {
					g.drawString(rand, 10 * i + 3, DownNum);
				} else {
					g.drawString(rand, 10 * i + 3, UpNum);
				}
			}
			// g.drawString(rand,11*i+2,15);
			// g.drawString(rand,11*i+1,15);
		}

		g.dispose();
		ImageIO.write(image, "JPEG", response.getOutputStream());
		session.setAttribute(IConstants.ADMIN_LOGIN_CODE, sRand);
	}

	/**
	 * 生成验证码数据
	 * 
	 * @param StartNumC
	 * @param EndNumC
	 * @return
	 */
	Color getRandColor(int StartNumC, int EndNumC) {
		Random random = new Random();
		if (StartNumC > 255)
			StartNumC = 255;
		if (EndNumC > 255)
			EndNumC = 255;
		int r = StartNumC + random.nextInt(EndNumC - StartNumC);
		int g = StartNumC + random.nextInt(EndNumC - StartNumC);
		int b = StartNumC + random.nextInt(EndNumC - StartNumC);
		return new Color(r, g, b);
	}
}